package com.scap.dfs.dao.impl;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.persister.entity.AbstractEntityPersister;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.scap.dfs.dao.DailyCalFormulaConfigDao;
import com.scap.dfs.model.DailyCalFormulaConfig;
import com.scap.dfs.model.DailyCalFormulaConfigPK;
import com.scap.dfs.model.Department;

@Repository
public class DailyCalFormulaConfigDaoImpl implements DailyCalFormulaConfigDao {

	
	final static Logger logger = Logger.getLogger(DailyCalFormulaConfigDaoImpl.class);
	
	@Autowired
	SessionFactory sessionFactory;
	
	@Override
	public boolean insert(DailyCalFormulaConfig dailyCalFormulaConfig) {
		DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
		Date date = new Date();
		dailyCalFormulaConfig.setUpdateTime(dateFormat.format(date));
		dateFormat = new SimpleDateFormat("yyyyMMdd");
		dailyCalFormulaConfig.setUpdateDate(dateFormat.format(date));
		
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		try{
			Serializable result = null;
			result = session.save(dailyCalFormulaConfig);
			System.out.println("Result form add DailyCalFormulaConfig : "+result);
			tx.commit();
		}
		catch(Exception e){
			logger.error(e);
			tx.rollback();
			return false;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return true;
	}

	@Override
	public boolean update(DailyCalFormulaConfig d1) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		
		try{
			
			DailyCalFormulaConfig d2 = (DailyCalFormulaConfig) session.get(DailyCalFormulaConfig.class, d1.getId());
			d2.getId().setAdmissionType(d1.getId().getAdmissionType()!=null?d1.getId().getAdmissionType():d2.getId().getAdmissionType());
			d2.getId().setInvoiceType(d1.getId().getInvoiceType()!=null?d1.getId().getInvoiceType():d2.getId().getInvoiceType());
			d2.setSharingBaht(d1.getSharingBaht()!=null?d1.getSharingBaht():d2.getSharingBaht());
			d2.setSharingPercent(d1.getSharingPercent()!=null?d1.getSharingPercent():d2.getSharingPercent());
			d2.setTaxType(d1.getTaxType()!=null?d1.getTaxType():d2.getTaxType());
			
			d2.getId().setFormulaId(d1.getId().getFormulaId()!=null?d1.getId().getFormulaId():d2.getId().getFormulaId());
			d2.getId().setHospitalCode(d1.getId().getHospitalCode()!=null?d1.getId().getHospitalCode():d2.getId().getHospitalCode());
			d2.getId().setSharingBegin(d1.getId().getSharingBegin()!=null?d1.getId().getSharingBegin():d2.getId().getSharingBegin());
			d2.getId().setSharingEnd(d1.getId().getSharingEnd()!=null?d1.getId().getSharingEnd():d2.getId().getSharingEnd());
			d2.getId().setVar1Value(d1.getId().getVar1Value()!=null?d1.getId().getVar1Value():d2.getId().getVar1Value());
			d2.getId().setVar2Value(d1.getId().getVar2Value()!=null?d1.getId().getVar2Value():d2.getId().getVar2Value());
			d2.getId().setVar3Value(d1.getId().getVar3Value()!=null?d1.getId().getVar3Value():d2.getId().getVar3Value());
	
			
			DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
			Date date = new Date();
			d2.setUpdateTime(dateFormat.format(date));
			dateFormat = new SimpleDateFormat("yyyyMMdd");
			d2.setUpdateDate(dateFormat.format(date));
			session.update(d2);
			
			tx.commit();
		}
		catch(Exception e){
			logger.error(e);
			tx.rollback();
			return false;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return true;
	}

	@Override
	public boolean delete(DailyCalFormulaConfigPK pk) {
		DailyCalFormulaConfig dailyCalFormulaConfig = new DailyCalFormulaConfig();
		dailyCalFormulaConfig.setId(pk);
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		try{
			session.delete(dailyCalFormulaConfig);
			tx.commit();
		}
		catch(Exception e){
			logger.error(e);
			tx.rollback();
			return false;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return true;
	}

	@Override
	public DailyCalFormulaConfig findById(DailyCalFormulaConfigPK pk) {
		Session session = sessionFactory.openSession();
		DailyCalFormulaConfig dailyCalFormulaConfig = null;
		try{
			dailyCalFormulaConfig = (DailyCalFormulaConfig) session.get(DailyCalFormulaConfig.class,pk);
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return dailyCalFormulaConfig;
	}

	@Override
	public List<DailyCalFormulaConfig> getLisByHospitalCodeAndFormulaId(String hospitalCode,int formulaId) {
		Session session = sessionFactory.openSession();
		List<DailyCalFormulaConfig> dailyCalFormulaConfigs = null;
		try{
			Criteria cr = session.createCriteria(DailyCalFormulaConfig.class);
			cr.add(Restrictions.like("id.hospitalCode",hospitalCode));
			cr.add(Restrictions.eq("id.formulaId",formulaId));
			dailyCalFormulaConfigs = cr.list();			
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return dailyCalFormulaConfigs;
	}

	@Override
	public List getListPerPage(int amount, int page, String orderByColumnName,
			String ascOrDesc) {
		
		Session session = sessionFactory.openSession();
		int firstElement = amount*(page-1);
		List<DailyCalFormulaConfig> dailyCalFormulaConfigs = null;
		
		try{
			Criteria cr = session.createCriteria(DailyCalFormulaConfig.class);
			cr.setFirstResult(firstElement);
			cr.setMaxResults(amount);
			dailyCalFormulaConfigs = cr.list();			
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return dailyCalFormulaConfigs;

	}

	@Override
	public List findByAttribute(DailyCalFormulaConfig dailyCalFormulaConfig) {
		
		Session session = sessionFactory.openSession();
		List<DailyCalFormulaConfig> dailyCalFormulaConfigs = null;
		
		try{
			Criteria cr = session.createCriteria(DailyCalFormulaConfig.class);
			
			if(dailyCalFormulaConfig.getId().getAdmissionType()!=null)cr.add(Restrictions.like("admissionType",dailyCalFormulaConfig.getId().getAdmissionType()));
			if(dailyCalFormulaConfig.getId().getInvoiceType()!=null)cr.add(Restrictions.like("invoiceType", dailyCalFormulaConfig.getId().getInvoiceType()));
			if(dailyCalFormulaConfig.getSharingBaht()!=null)cr.add(Restrictions.eq("sharingBaht",dailyCalFormulaConfig.getSharingBaht()));
			if(dailyCalFormulaConfig.getSharingPercent()!=null)cr.add(Restrictions.like("sharingPercent",dailyCalFormulaConfig.getSharingPercent()));
			if(dailyCalFormulaConfig.getTaxType()!=null)cr.add(Restrictions.like("taxType",dailyCalFormulaConfig.getTaxType()));
			if(dailyCalFormulaConfig.getId().getFormulaId()!=null)cr.add(Restrictions.eq("id.formulaId",dailyCalFormulaConfig.getId().getFormulaId()));
			if(dailyCalFormulaConfig.getId().getHospitalCode()!=null)cr.add(Restrictions.like("id.hospitalCode",dailyCalFormulaConfig.getId().getHospitalCode()));
			if(dailyCalFormulaConfig.getId().getSharingBegin()!=null)cr.add(Restrictions.eq("id.sharingBegin",dailyCalFormulaConfig.getId().getSharingBegin()));
			if(dailyCalFormulaConfig.getId().getSharingEnd()!=null)cr.add(Restrictions.eq("id.sharingEnd",dailyCalFormulaConfig.getId().getSharingEnd()));
			if(dailyCalFormulaConfig.getId().getVar1Value()!=null)cr.add(Restrictions.like("id.var1Value",dailyCalFormulaConfig.getId().getVar1Value()));
			if(dailyCalFormulaConfig.getId().getVar2Value()!=null)cr.add(Restrictions.like("id.var2Value",dailyCalFormulaConfig.getId().getVar2Value()));
			if(dailyCalFormulaConfig.getId().getVar3Value()!=null)cr.add(Restrictions.like("id.var3Value",dailyCalFormulaConfig.getId().getVar3Value()));
			
			cr.addOrder(Order.asc("id.hospitalCode"));
			cr.addOrder(Order.asc("id.formulaId"));
			dailyCalFormulaConfigs = cr.list();			
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return dailyCalFormulaConfigs;

	}

	@Override
	public List findByAttributePerPage(
			DailyCalFormulaConfig dailyCalFormulaConfig, int amount, int page,
			String orderByColumnName, String ascOrDesc) {
		
		Session session = sessionFactory.openSession();
		List<DailyCalFormulaConfig> dailyCalFormulaConfigs = null;
		int firstElement = amount*(page-1);
		
		try{
			
			Criteria cr = session.createCriteria(DailyCalFormulaConfig.class);
			
			if(dailyCalFormulaConfig.getId().getAdmissionType()!=null)cr.add(Restrictions.like("admissionType",dailyCalFormulaConfig.getId().getAdmissionType()));
			if(dailyCalFormulaConfig.getId().getInvoiceType()!=null)cr.add(Restrictions.like("invoiceType", dailyCalFormulaConfig.getId().getInvoiceType()));
			if(dailyCalFormulaConfig.getSharingBaht()!=null)cr.add(Restrictions.eq("sharingBaht",dailyCalFormulaConfig.getSharingBaht()));
			if(dailyCalFormulaConfig.getSharingPercent()!=null)cr.add(Restrictions.like("sharingPercent",dailyCalFormulaConfig.getSharingPercent()));
			if(dailyCalFormulaConfig.getTaxType()!=null)cr.add(Restrictions.like("taxType",dailyCalFormulaConfig.getTaxType()));
			if(dailyCalFormulaConfig.getId().getFormulaId()!=null)cr.add(Restrictions.eq("id.formulaId",dailyCalFormulaConfig.getId().getFormulaId()));
			if(dailyCalFormulaConfig.getId().getHospitalCode()!=null)cr.add(Restrictions.like("id.hospitalCode",dailyCalFormulaConfig.getId().getHospitalCode()));
			if(dailyCalFormulaConfig.getId().getSharingBegin()!=null)cr.add(Restrictions.eq("id.sharingBegin",dailyCalFormulaConfig.getId().getSharingBegin()));
			if(dailyCalFormulaConfig.getId().getSharingEnd()!=null)cr.add(Restrictions.eq("id.sharingEnd",dailyCalFormulaConfig.getId().getSharingEnd()));
			if(dailyCalFormulaConfig.getId().getVar1Value()!=null)cr.add(Restrictions.like("id.var1Value",dailyCalFormulaConfig.getId().getVar1Value()));
			if(dailyCalFormulaConfig.getId().getVar2Value()!=null)cr.add(Restrictions.like("id.var2Value",dailyCalFormulaConfig.getId().getVar2Value()));
			if(dailyCalFormulaConfig.getId().getVar3Value()!=null)cr.add(Restrictions.like("id.var3Value",dailyCalFormulaConfig.getId().getVar3Value()));
			
			if(ascOrDesc=="desc"||ascOrDesc.equals("desc")){
				cr.addOrder(Order.desc(orderByColumnName));
			}
			else{
				cr.addOrder(Order.asc(orderByColumnName));
			}
			cr.setFirstResult(firstElement);
			cr.setMaxResults(amount);
			dailyCalFormulaConfigs = cr.list();			
			
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return dailyCalFormulaConfigs;
	}

	@Override
	public String getAttributeNameByColumnName(String columnName) {
	
		AbstractEntityPersister aep=((AbstractEntityPersister)sessionFactory.getClassMetadata(DailyCalFormulaConfig.class));  
		String[] properties=aep.getPropertyNames();  
		try{
		
			
			for(int nameIndex=0;nameIndex!=properties.length;nameIndex++){  
	//			   System.out.println("Property name: "+properties[nameIndex]);  
				   String[] columns=aep.getPropertyColumnNames(nameIndex);  
				   for(int columnIndex=0;columnIndex!=columns.length;columnIndex++){  
					  if(columns[columnIndex].equals(columnName)||columns[columnIndex]==columnName){
						  return properties[nameIndex];
					  }
	//			      System.out.println("Column name: "+columns[columnIndex]);  
				   }  
				} 
			
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		
		return null;
	}


}
